﻿package com.skcc.cop.mrtaxi.biz.destination;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.skcc.cop.mrtaxi.BaseActivity;
import com.skcc.cop.mrtaxi.R;
import com.skp.Tmap.TMapMarkerItem;
import com.skp.Tmap.TMapPoint;
import com.skp.Tmap.TMapView;



public class DriverMap extends BaseActivity {


	public int back;
	private LinearLayout mapLayout;
	private TMapView mMapView = null;
	private LocationManager locationManager;
	private String provider;
	private boolean getMyLocation;
	double curLatitude, curLongitude;
//	private Handler mChildHandler;
	public Location location = null;
	private TMapMarkerItem tItem = new TMapMarkerItem();
	
	Criteria criteria;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.driver_map);	
		
		this.mapLayout = (LinearLayout)findViewById(R.id.framelayout_map);
		mMapView = new TMapView(this);
		mMapView.setSKPMapApiKey("c7c9ee81-1a9c-3c7e-9899-3b9c19a0dac2");
		
		mapLayout.addView(mMapView);
		
		
		
		
		getMyLocation = false;
		
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    	criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
        criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
        
        provider = locationManager.getBestProvider(criteria, true);
		
        if(provider == null){
        	
        	AlertDialog.Builder ab = new AlertDialog.Builder(DriverMap.this);
			ab.setMessage("위치 정보를 수신할 수 없습니다. 환경설정에서 GPS사용 또는 3G/Wi-Fi위치사용 기능을 ON으로 설정해주세요.");
			
			ab.setPositiveButton("확인", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
					dialog.dismiss();
					
					back = 1;
				}
			});
			ab.setNegativeButton("취소", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					finish();
				}
			}).show(); 
        	
        	
        }else{
        	
        	checkGPS();
        	
        }
        
	}
	

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		if(back == 1){
			
			Toast.makeText(DriverMap.this, "다시 실행해 주세요", Toast.LENGTH_SHORT).show();
			
		}

	}
	

	protected void getConnection(){
		TMapView tmapview = new TMapView(this);
		
		tmapview.setSKPMapApiKey("c7c9ee81-1a9c-3c7e-9899-3b9c19a0dac2");
		
		

		double Latitude = curLatitude;
		double Longitude = curLongitude;
		
		//double Longitude = tpoint.getLongitude();
		
		tmapview.setLanguage(tmapview.LANGUAGE_KOREAN);
		tmapview.setIconVisibility(true);
		tmapview.setZoomLevel(10);
		tmapview.setMapType(tmapview.MAPTYPE_STANDARD);
		tmapview.setCompassMode(true);
		tmapview.setTrackingMode(true);
		tmapview.setCenterPoint(Longitude, Latitude);
		
		System.out.println("getConnection : " + "\n" + Latitude + "\n" + Longitude );

		String name = "내위치";
		TMapPoint tpoint1 = new TMapPoint(Latitude, Longitude);
		
		tItem.setID(name);
		tItem.setTMapPoint(tpoint1);
		tItem.setName(name);
		tItem.setVisible(tItem.VISIBLE);
		
		//내위치
		Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(),R.drawable.map_pin_red);		
		tItem.setIcon(bitmap);
		
		mMapView.addMarkerItem(name, tItem);
		mMapView.setCenterPoint(Longitude,Latitude);
		mMapView.MapZoomIn();
		
		
		
	}
	
	
	private void checkGPS() {
		// TODO Auto-generated method stub
		
		Criteria criteria = new Criteria();
	    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
        criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
	     
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        
        provider = locationManager.getBestProvider(criteria, true);
        
		System.out.println("provider : " + provider);
		
		//Toast.makeText(MainActivity.this, provider, Toast.LENGTH_SHORT).show();
		
		
		//locationManager.requestLocationUpdates(provider, 0, 30, locationListener);
	    
	    
	    Toast.makeText(DriverMap.this, "GPS 위치 정보를 얻어오는 중 입니다.", Toast.LENGTH_SHORT).show();
	    
	    
        
        Handler mHandler = new Handler();
        mHandler.postDelayed(new Runnable()
        {
			public void run() 
			{
				if(!getMyLocation)
				{
					//"GPS가 수신되지 않습니다. 위치 제공자를 네트워크로 변경합니다."
					Toast.makeText(DriverMap.this, "GPS가 수신되지 않습니다. 위치 제공자를 네트워크로 변경합니다.", Toast.LENGTH_SHORT).show();
					
					//위치 제공자가 네트워크일 경우 현재 위치와의 정확도가 낮습니다."
					Toast.makeText(DriverMap.this, "위치 제공자가 네트워크일 경우 현재 위치와의 정확도가 낮습니다.", Toast.LENGTH_SHORT).show();
					
					Handler mHandler = new Handler();
			        mHandler.postDelayed(new Runnable(){
						public void run() {
							if(!getMyLocation){
								if(provider != null && provider.trim().length() > 0){
									locationManager.removeUpdates(locationListener);
									locationManager.requestLocationUpdates(provider, 0, 30, locationListener);
									
									Handler mHandler = new Handler();
							        mHandler.postDelayed(new Runnable()
							        {
										public void run() 
										{
											if(!getMyLocation)
											{
												location = locationManager.getLastKnownLocation(provider);
												//Location location = locationManager.isProviderEnabled((provider);
												if(location != null){
													getMyLocation = true;
											        
													//System.out.println("kukuku11111:");
													
											        curLatitude 	= location.getLatitude();
													curLongitude 	= location.getLongitude();
													
													String ku1 = Double.toString(curLatitude);
													String ku2 = Double.toString(curLongitude);
													
													
													Toast.makeText(DriverMap.this, ku1 + "\n" + ku2, Toast.LENGTH_SHORT).show();
													
													System.out.println("kukuku22222  :  " + curLatitude);
													System.out.println("kukuku22222  :  " + curLongitude);
	
													getConnection();
													
													//mChildHandler.sendEmptyMessage(0);
											    	
													
												} else {
													AlertDialog.Builder builder = new AlertDialog.Builder(DriverMap.this);
													 
													 builder.setTitle("위치서비스 동의하시겠습니까?");
													 builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
														
														@Override
														public void onClick(DialogInterface dialog, int which) {
															// TODO Auto-generated method stub
															startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
										
														}
														}).setOnCancelListener(new DialogInterface.OnCancelListener() {
														@Override
														public void onCancel(DialogInterface dialog) {
															finish();
														}
													});
													builder.setNegativeButton("취소", new DialogInterface.OnClickListener() {
														
														@Override
														public void onClick(DialogInterface arg0, int arg1) {
															// TODO Auto-generated method stub
															finish();
															Toast.makeText(DriverMap.this, "위치설정에 동의하셔야 합니다.", Toast.LENGTH_SHORT).show();
														}
													});
													builder.show();
												}
											}
										}
							        }, 3000);
								}else{
									 AlertDialog.Builder builder = new AlertDialog.Builder(DriverMap.this);
									 
									 builder.setTitle("위치서비스 동의하시겠습니까?");
									 builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
										
										@Override
										public void onClick(DialogInterface dialog, int which) {
											// TODO Auto-generated method stub
											startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
						
										}
										}).setOnCancelListener(new DialogInterface.OnCancelListener() {
										@Override
										public void onCancel(DialogInterface dialog) {
											finish();
										}
									});
									builder.setNegativeButton("취소", new DialogInterface.OnClickListener() {
										
										@Override
										public void onClick(DialogInterface arg0, int arg1) {
											// TODO Auto-generated method stub
											finish();
											Toast.makeText(DriverMap.this, "위치설정에 동의하셔야 합니다.", Toast.LENGTH_SHORT).show();
										}
									});
									builder.show();
								}
							}
						}
			        }, 3000);
				}
			}
        }, 5000);
        
		
	}
	
	
	LocationListener locationListener = new LocationListener() {
		
		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
			System.out.println("111111111111");
		}
		
		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
			System.out.println("222222222");
		}
		
		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
		}
		
		@Override
		public void onLocationChanged(Location location) {
			// TODO Auto-generated method stub
			
			System.out.println("44444444444");
			
		}
	};
	
	
}